<?php
	####################################################
	# Cipher 암호화/복호화                             #
	####################################################
	# 아파치 모듈 의존성 mycrypt_encrypt

	class Cipher {
		public static $encrypt_hash = 'naiyumie';
		public static function encrypt($text) {
			if (function_exists('mcrypt_encrypt')) {
				return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, Cipher::$encrypt_hash, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
			} else {
				return $text;
			}
		}

		public static function decrypt($text) {
			if (function_exists('mcrypt_decrypt')) {
				return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, Cipher::$encrypt_hash, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
			} else {
				return $text;
			}
		}

		public static function encrypting($value, $mode=0) {
			if ( $mode )
			{
				$md5 = md5sum();
				$GLOBALS['_SESSION']['Xmd5'] = $md5;
			}
			else
			{
				$md5 = "c54dd57dbd5493bfcb452b0ee082ebbc";
			}

			$value = serialize($value);
			$padSize = 16 - (strlen ($value) % 16);
			$value = $value . str_repeat (chr ($padSize), $padSize) ;
			$output = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $md5, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;
			$output = str2hex(base64_encode($output));
			return $output;
		}

		public static function decrypting($value, $mode=0) {
			if ( $mode )
			{
				$md5 = $_SESSION['Xmd5'];
			}
			else
			{
				$md5 = "c54dd57dbd5493bfcb452b0ee082ebbc";
			}

			$value = base64_decode(hex2str($value));
			$output = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $md5, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;

			$valueLen = strlen ($output) ;
			if ( $valueLen % 16 > 0 )
				$output = "";

			$padSize = ord ($output{$valueLen - 1}) ;
			if ( ($padSize < 1) or ($padSize > 16) )
				$output = "";

			for ($i = 0; $i < $padSize; $i++)
			{
				if ( ord ($output{$valueLen - $i - 1}) != $padSize )
					$output = "";
			}
			$output = substr ($output, 0, $valueLen - $padSize) ;
			$output = unserialize($output);
			return $output;
		}
	}
?>